package cn.myjerry.thread.syn;

public class SynDemo01 {
	public static void main(String[] args) {
		// 真实角色
		Web12306 web = new Web12306();
		// 代理
		Thread t1 = new Thread(web, "路人甲");
		Thread t2 = new Thread(web, "路人乙");
		Thread t3 = new Thread(web, "路人丙");

		// 启动线程
		t1.start();
		t2.start();
		t3.start();
	}
}

class Web12306 implements Runnable {
	private int num = 10;
	private boolean flag = true;
	
	@Override
	public void run() {
		while(flag) {
			try {
				test03();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public void test03() throws InterruptedException {
		synchronized(this) {
			if(num <= 0) {
				this.flag = false;
				return;
			}
			Thread.sleep(500);
			System.out.println(Thread.currentThread().getName() + "抢到了" + num-- + "...");
		}
	}
	
	public synchronized void test02() throws InterruptedException {
		if(num <= 0) {
			this.flag = false;
			return;
		}
		Thread.sleep(500);
		System.out.println(Thread.currentThread().getName() + "抢到了" + num-- + "...");
	}
	
	// 线程不安全
	public void test01() throws InterruptedException {
		if(num <= 0) {
			this.flag = false;
			return;
		}
		Thread.sleep(500);
		System.out.println(Thread.currentThread().getName() + "抢到了" + num-- + "...");
	}
	
}